package com.hjh.gameforum.controller;

import com.hjh.gameforum.dto.CategoryDto;
import com.hjh.gameforum.entity.Category;
import com.hjh.gameforum.result.Result;
import com.hjh.gameforum.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
@Tag(name = "分类管理", description = "分类相关操作")
@Slf4j
public class CategoryController {
    private final CategoryService categoryService;

    private final RedisTemplate redisTemplate;

    @GetMapping("/all")
    @Operation(summary = "获取所有分类")
    public Result getAllCategories(){
        log.info("获取所有分类");
        String key = "categories";
        Object cachedObject = redisTemplate.opsForValue().get(key);
        if (cachedObject != null) {
            return Result.success(cachedObject);
        }
        List<Category> categories = categoryService.getAllCategories();
        redisTemplate.opsForValue().set(key, categories);
        return Result.success(categories);
    }

    @PostMapping
    @Operation(summary = "创建分类")
    public Result createCategory(@RequestBody CategoryDto categoryDto) {
        log.info("创建分类: {}",categoryDto);
        categoryService.createCategory(categoryDto);
        return Result.success();
    }

    @PutMapping("/{categoryId}")
    @Operation(summary = "更新分类")
    public Result updateCategory(@PathVariable Long categoryId, @RequestBody CategoryDto categoryDto) {
        log.info("更新分类: {}",categoryDto);
        categoryService.updateCategory(categoryId, categoryDto);
        return Result.success();
    }

    @DeleteMapping("/{categoryId}")
    @Operation(summary = "删除分类")
    public Result deleteCategory(@PathVariable Long categoryId) {
        log.info("删除分类: {}",categoryId);
        categoryService.deleteCategory(categoryId);
        return Result.success();
    }
}

